package sampleapp.logic;

import sampleapp.dao.UserDao;
import sampleapp.model.Profile;
import sampleapp.model.User;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;

@Singleton
public class UserLogic {

	@Inject
	private UserDao userDao;

	@Transactional
	public User login(String email, String password) {
		User user = userDao.getUserByEmail(email);
		if (user != null && user.getPassword().equals(password))
			return user;
		else
			return null;
	}

	@Transactional
	public boolean registerUser(String email, String password) {
		User databaseUser = userDao.getUserByEmail(email);
		if (databaseUser != null) {
			return false; 
		}
		
		Profile profile = new Profile();
		profile.setProfileName(email);
		
		User user = new User();
		user.setEmail(email);
		user.setPassword(password);
		user.setAdminFlag(false);
		user.setProfile(profile);
		try {
			userDao.save(user);			
		}
		catch (Throwable t) {
			System.out.println("ERROR!");
		}
		return true;
	}
}
